import _ from 'lodash'
import mysql from 'mysql'
import env from '../env'

const pool = mysql.createPool({
	connectionLimit: 10,
	host: env.DB_HOST,
	user: env.DB_USER,
	password: env.DB_PASSWORD,
	database: env.DB_DATABASE
})

/**
 * 查询数据库
 * @param query 查询语句
 * @example
 *  db(`SELECT * FROM ${table}`)
 *  db(`SELECT field1, field2 FROM ${table}`)
 *  db(`INSERT INTO ${table} (field1, field2) VALUES (${value1}, ${value2})`)
 *  db(`UPDATE ${table} SET field1=${value1}, field2=${value2} WHERE id=${id}`)
 *  db(`DELETE FROM ${table} WHERE id=${id}`)
 */
const db = async (query: string): Promise<any> =>
	new Promise((resolve, reject) => {
		pool.getConnection((err, conn) => {
			if (err) return reject('获取连接失败：' + err)
			conn.query(query, (err, res) => {
				if (err) return reject('操作数据库失败：' + err)
				resolve(res)
				conn.release()
			})
		})
	})

class Table<TableName, Fields, Field extends keyof Fields> {
	tableName: TableName
	fields: Fields
	constructor(tableName: TableName, fields: Fields) {
		this.tableName = tableName
		this.fields = fields
	}
	async select<SelectFields extends keyof Fields>(
		fields: Field[]
	): Promise<
		[
			{
				[K in SelectFields]: typeof this.fields[K]
			}
		]
	> {
		const selectFieldsStr = fields.join(',') || '*'
		return await db(`SELECT ${selectFieldsStr} FROM ${this.tableName}`)
	}
}

export default db
